﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Globalization;

namespace SmartMap.Domain.Common
{
    public static class ControlExtensions
    {
        /// <summary>
        /// Register a javascript link in the head of a control.
        /// </summary>
        /// <param name="control">The control that is used to register the style sheet.</param>        
        /// <param name="location">The location of the javascript link.</param>
        public static void RegisterJavaScriptLink(this Control control, string location)
        {
            // Make sure that the style sheet is only added one time.
            String applicationName = HttpRuntime.AppDomainAppVirtualPath;
            if (!applicationName.EndsWith("/", StringComparison.CurrentCultureIgnoreCase))
            {
                applicationName += "/";
            }
            string safeLocation = location;
            if (safeLocation.StartsWith("~", StringComparison.CurrentCultureIgnoreCase))
            {
                safeLocation = safeLocation.Replace("~/", applicationName);
            }

            String pageKey = "s." + safeLocation;
            if (!control.Page.Items.Contains(pageKey))
            {
                control.Page.Items.Add(pageKey, string.Empty);

                String javaScriptLink = String.Format(CultureInfo.CurrentCulture, "<script src=\"{0}\" type=\"text/javascript\"></script>",
                                                      safeLocation);
                control.Page.Header.Controls.Add(new LiteralControl(javaScriptLink));
            }
        }
    }
}
